package com.yindian.cos.easy.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yindian.cos.easy.security.authentication.login.UserDetail;
import com.yindian.cos.easy.security.authentication.token.AbstractTokenFactory;
import com.yindian.cos.easy.security.authentication.token.Token;
import com.yindian.cos.easy.security.authentication.token.TokenStore;
import com.yindian.cos.easy.security.entity.User;
import com.yindian.cos.easy.security.form.CustomFormUserDetail;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.smsCode.CustomSmsCodeUserDetail;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 登录成功处理器
 *
 * @author zhangchuanhao
 * @create 2018/11/19
 */
@Log4j2
@Component
public class CustomLoginSuccessHandler implements LoginSuccessHandler {

    @Autowired
    AbstractTokenFactory tokenFactory;

    @Autowired
    TokenStore redisTokenStore;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    EasySecurityProperties easySecurityProperties;

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response, UserDetail userDetail) throws IOException {
        Token token = tokenFactory.builder(userDetail);
        String url = getUrl(token, userDetail);
        response.sendRedirect(url);
    }

    public static String getUrl(Token token, UserDetail userDetail) throws UnsupportedEncodingException {
        User user = null;
        if (userDetail instanceof CustomFormUserDetail) {
            user = ((CustomFormUserDetail) userDetail).getUser();
        } else if (userDetail instanceof CustomSmsCodeUserDetail) {
            user = ((CustomSmsCodeUserDetail) userDetail).getUser();
        }
        String url = "/login-success";

        url += "?userId=" + user.getUserId();
        url += "&username=" + user.getUsername();
        url += "&nickName=" + URLEncoder.encode(user.getNickName(), "utf-8");

        url += "&accessToken=" + token.getAccessToken();
        url += "&accessTokenExpire=" + token.getAccessTokenExpire();

        url += "&refreshToken=" + token.getRefreshToken();
        url += "&refreshTokenExpire=" + token.getRefreshTokenExpire();
        return url;
    }
}
